<?php
/**
 * Created by jinqiang on 2024/8/21 13:33.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Op;


use App\Http\Models\Mysql\SsyAllocationIpurchaseListTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseTable;
use App\Http\Models\Mysql\SsyFeishuApprovalBindingTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Repository\FeishuRepository;
use Illuminate\Support\Facades\DB;

class IpurchaseService
{
    public function search($param)
    {
        $conn = (new SsyAllocationIpurchaseListTable());
        if($param['allocation_number'] ?? ""){
            $allocationNumbers = explode(",", str_replace("，", ",", $param['allocation_number']));
            $conn = count($allocationNumbers) > 1 ? $conn->whereIn('allocation_number', $allocationNumbers) : $conn->where('allocation_number', $param['allocation_number']);
        }
        if($param['adduser'] ?? ""){
            $conn = $conn->where('adduser', $param['adduser']);
        }
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', $param['status']);
        }
        if($param['wp_phone'] ?? ""){
            $conn = $conn->where('wp_phone', $param['wp_phone']);
        }
        if($param['wp_user'] ?? ""){
            $conn = $conn->where('wp_user', $param['wp_user']);
        }
        if($param['createtime'] ?? []){
            $start = $param['createtime'][0]." 00:00:00";
            $end = $param['createtime'][1]." 23:59:59";
            $conn = $conn->whereBetween('createtime', [$start, $end]);
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        $allocationNumbers = array_column($res['data'], 'allocation_number');
        $skuCodeMap = [];//内购的明细规格编码
        $approvalIdMap = [];//飞书审批ID
        if(!empty($allocationNumbers)){
            //内购的明细规格编码
            $ipurchaseOrders = (new SsyAllocationIpurchaseTable())->whereIn('allocation_number', $allocationNumbers)->get(['allocation_number', 'sku_code'])->toArray();
            foreach ($ipurchaseOrders as $item){
                $skuCodeMap[$item['allocation_number']][] = $item['sku_code'];
            }
            //飞书审批id
            $approvalList = (new SsyFeishuApprovalBindingTable())->whereIn('data_id', $allocationNumbers)->where('status', 1)
                ->get(['data_id', 'instance_code'])->toArray();
            foreach ($approvalList as $item){
                $approvalIdMap[$item['data_id']] = $item['instance_code'];
            }
        }
        foreach($res['data'] as &$item){
            $item['sku_codes'] = $skuCodeMap[$item['allocation_number']];
            $item['approval_id'] = $approvalIdMap[$item['allocation_number']] ?? "";
        }
        unset($item);
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function detail($allocationNumber)
    {
        $allocationObj = (new SsyAllocationIpurchaseListTable())->where('allocation_number', $allocationNumber)->first()->toArray();
        $orders = (new SsyAllocationIpurchaseTable())->where('allocation_number', $allocationNumber)->get()->toArray();
        $discount = (Double)$allocationObj['discount'];
        foreach($orders as &$item){
            $item['discount_amount'] = round((Int)$item['num'] * (Double)$item['price'] * $discount, 2);
        }
        unset($item);
        $allocationObj['list'] = $orders;
        $allocationObj['images'] = preg_match("/(http.*?(?:png|jpg|jpeg))/is", $allocationObj['images'], $d) ? $d[1] : $allocationObj['images'];
        return $allocationObj;
    }

    //内购审批
    public function approval($param)
    {
        $user = auth()->guard("api")->user()->toArray();
        $subjects = array_column(config("scm.subject"), null, 'is_subject');
        $isSubject = $user['is_subject'];
        $discount = $subjects[$isSubject]['discount'];
        $detail = $param['detail'] ?? [];
        if(empty($detail)){
            return ['code' => -1, 'msg' => '请提交归还任务明细'];
        }
        //同一账号每月只能购买一次
        $exist = (new SsyAllocationIpurchaseListTable())->where('adduser', $user['name'])->where('status', [0, 1])->where('is_subject', $isSubject)
            ->whereBetween('createtime', [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')])->exists();
        if($exist){
            return ['code' => -1, '同一账号每月只能购买一次噢！！！'];
        }
        $skuCodes = array_column($detail, 'sku_code');
        $allocationNumber = "NG".$user['id'].date('YmdHis');
        //生成明细表
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["type_no","product_code","product_name","img"])->toArray();
        $jyMap = array_column($jyList, null, 'product_code');
        $totalNum = 0;
        $totalPrice = 0;
        $tableStr = "";
        DB::beginTransaction();
        foreach ($detail as $item){
            if((Int)$item['num'] <= 0 || empty($item['price'])){
                DB::rollBack();
                return ['code' => -1, 'msg' => '数量或价格 错误'];
            }
            $orderData = [
                "allocation_number" => $allocationNumber,
                "type_name" => $jyMap[$item['sku_code']]['product_name'],
                "type_no" => $jyMap[$item['sku_code']]['type_no'],
                "img" => $jyMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => (Int)$item['num'],
                "price" => (Double)$item['price'],
                "types" => 0,//1 借出转内购 0 普通内购
                "createtime" => date("Y-m-d H:i:s")
            ];
            $res = (new SsyAllocationIpurchaseTable())->createData($orderData);
            if($res['code'] !== 0){
                DB::rollBack();
                return $res;
            }
            $totalNum += (Int)$item['num'];
            $totalPrice += (Int)$item['num'] * (Double)$item['price'];
            $tableStr .= '[{"id": "type_name","type":"input","value":"'.$jyMap[$item['sku_code']]['product_name'].'"},{"id": "sku_code","type":"input","value":"'
                .$item['sku_code'].'"},{"id":"num","type":"input","value":"'.$item['num'].'"},{"id":"price","type":"input","value":"'.$item['price'].'"}],';
        }
        $tableStr = rtrim($tableStr,',');
        $discountAmount = round($totalPrice*$discount, 2);
        //生成调拨表
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "wp_phone" => $param['wp_phone'],
            "wp_province" => $param['wp_province'],
            "wp_city" => $param['wp_city'],
            "wp_area" => $param['wp_area'] ?? "",
            "wp_address" => $param['wp_address'],
            "wp_user" => $param['wp_user'],
            "adduser" => $user['name'],
            "total_num" => $totalNum,
            "total_price" => $totalPrice,
            "images" => $param['img'],
            "types" => 0,//1 借出转内购 0 普通内购
            "jc_number" => "",
            "is_subject" => $isSubject,
            "discount" => $discount,
            "discount_amount" => $discountAmount,
            "createtime" => date("Y-m-d H:i:s")
        ];
        $res = (new SsyAllocationIpurchaseListTable())->createData($allocationData);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        //发起飞书审批
        $date = date("Y-m-d\TH:i:s+H:00",time());
        $approvalSubject = in_array($isSubject, ['kz', 'mz', 'qyx']) ? 'kz' : $isSubject;
        $fsUserId = $user[$approvalSubject.'_feishu_user_id'];
        $fsOpenId = $user[$approvalSubject.'_feishu_open_id'];
        $fsApprovalCode = $subjects[$approvalSubject]['ng_approval_code'];
        //$fsApprovalCode = "8C76D3A0-8058-4D3D-BE4B-8E1999868FA7";//内部测试
        $subjectLabelMap = ["kz" => "mclll0dd-h0ojnoa1d1h-0", "mz" => "mclll0dd-f6fvl1r4b0f-0", "qyx" => "mclll0dd-xa2013l2ur-0"];
        //品牌字段
        $brandStr = $approvalSubject == "kz" ? '{"id":"is_subject","type":"radioV2","value":"'.$subjectLabelMap[$isSubject].'"},' : "";
        $postData = [
            "approval_code" => $fsApprovalCode,
            "user_id" => $fsUserId,
            "open_id" => $fsOpenId,
            "form" => '['.$brandStr.'{"id":"createtime","type":"date","value":"'.$date.'"},{"id":"allocation_number","type":"input","value":"'.$allocationNumber
                .'"},{"id":"total_num","type":"input","value":"'.$totalNum.'"},{"id":"total_price","type":"input","value":"'.$totalPrice
                .'"},{"id":"discount","type":"input","value":"'.$discount.'"},{"id":"discount_total_price","type":"input","value":"'.$discountAmount
                .'"},{"id": "detaillist","type": "fieldList","value": ['.$tableStr.']},{"id":"wp_address","type":"textarea","value":"'
                .$param['wp_user'].$param['wp_phone'].$param['wp_province'].$param['wp_city'].($param['wp_area']??"")
                .$param['wp_address'].'"},{"id":"remark","type":"textarea","value":"'.$param['img'].'"},{"id":"images","type":"image","value":["'.$param['img'].'"]}]'
        ];
        $res = (new FeishuRepository($approvalSubject))->createApproval($postData);
        if($res['code'] != '0'){
            DB::rollBack();
            return ['code' => -1, 'msg' => '创建内购,失败!'.($res['msg'] ?? ""), 'data' => $res];
        }
        $createRes = (new SsyFeishuApprovalBindingTable())->createData([
            "instance_code" => $res['data']['instance_code'],
            "data_id" => $allocationNumber,
            "types" => 4,
            "createtime" => date('Y-m-d H:i:s')
        ]);
        if($createRes['code'] !== 0){
            DB::rollBack();
            return $createRes;
        }
        DB::commit();
        return $createRes;
    }
}
